package cn.jdy.plugins.admin;

import cn.jdy.authority.entity.User;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.authority.service.UserService;
import cn.jdy.plugins.entity.Info;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.InfoService;
import cn.jdy.plugins.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 会员收藏控制类
 */
@Controller
@RequestMapping("/info")
public class InfoCtrl extends BaseCtrl {
	@Autowired
	private InfoService infoService;
	@Autowired
	private MemberService memberService;// 会员分类业务处理类
	@Autowired
	private UserService userManage;
	
	/**
	 * 初始化
	 */
	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(required = false) Integer s) {
		ModelAndView mv = new ModelAndView("/operate/infoList.jsp");
		if(s!=null)
			switch(s) {
				case 1: mv.addObject("msg", "发送成功！");break;
				default: break;
			}
		return mv;
	}

	/**
	 * 发送消息初始化
	 */
	@RequestMapping("/send")
	public ModelAndView send(String userId) {
		ModelAndView mv = new ModelAndView("/operate/infoSend.jsp");
		if(userId != null) {
			Member member = memberService.find(userId);
			if(member != null) {
				mv.addObject("userId", userId);
				mv.addObject("userName", member.getUserName());
			}
		}
		return mv;
	}

	/**
	 * 我的消息信息
	 *
	 * @param bo
	 * @param currentPage
	 * @return
	 */
	@RequestMapping("/forinfo")
	@ResponseBody
	public Map<String, Object> forMyMessage(Info bo, Integer currentPage, Integer pageSize) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
//		Member memberinfo = getMember();
//		bo.setUserid(memberinfo.getId());	
		
		try {
			/************* 分页处理开始 ************/
			String Count = infoService.getInfoCount(bo);//查询我的消息信息总条数
			Map<String, Integer> map = getPageInfo(currentPage, pageSize, Count);//获取page信息
			currentPage = map.get("currentPage");
			pageSize = map.get("pageSize");
			Integer totalPage = map.get("totalPage");
			/************* 分页处理结束 ***********/

			bo.setPagestart((currentPage - 1) * pageSize);//查询起始值
			bo.setPagesize(pageSize);//查询条数
			List<Info> list = infoService.query(bo);

			for(Info info:list){
				if(info.getType().equals("4")){//前台用户
					Member member = memberService.find(info.getSendUserId());
					if(member!=null)
						info.setSendUsername(member.getUserName());
					/*客户发送给管理员的消息 客户小组*/
					info.setUsername(info.getUserid());
				}else {
					/*接收人*/
					if(info.getUserid()!=null) {
						Member member = memberService.find(info.getUserid());
						if(member!=null)
							info.setUsername(member.getUserName());
					}

					/*发送人*/
					if(info.getType().equals("2")){
						User user =  userManage.findOne("id", info.getSendUserId());
						if(user!=null)
							info.setSendUsername(user.getUsername());
					}else{
						info.setSendUsername("system");
					}
				}
			}
			
			jsonMap.put("dataList", list);
			jsonMap.put("iTotalRecords", Count);
			jsonMap.put("iTotalDisplayRecords", Count);

		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询我的消息信息错误", e);
		}
		return jsonMap;
	}

	
    /**
     * 根据id 查看消息信息
     * @param id
     * @return
     */
    @RequestMapping("/findInfoById")
    @ResponseBody
    public Map<String, Object>  findInfoById(String id){
    	Map<String, Object> jsonMap = new HashMap<String, Object>();
        try{
            if(null!=id && !"".equals(id)){
            	jsonMap.put("data",infoService.find(id));
            	jsonMap.put("status",200);
            }else{
            	jsonMap.put("status",500);
            }
        }catch (Exception e){
        	jsonMap.put("status",500);
            BaseLog.e(this.getClass(),"查找消息失败！",e);
        }

        return jsonMap;
    }
    
    
//	/**
//	 * 保存消息
//	 *
//	 * @param bo
//	 */
//	@RequestMapping("/save")
//	@ResponseBody
//	public Map<String, Object> save(Info bo) {
//		Map<String, Object> jsonMap = new HashMap<String, Object>();
//		try {
//			infoService.saveOrUpd(bo);
//			jsonMap.put("statusCode", 200);
//		} catch(Exception e) {
//			jsonMap.put("statusCode", 500);
//			BaseLog.e(this.getClass(), "保存消息异常", e);
//		}
//		return jsonMap;
//	}
	
	/**
	 * 删除消息
	 * @param id
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> del(String id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			infoService.delete(id);
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(this.getClass(), "删除消息异常", e);
		}
		return jsonMap;
	}

	/**
	 * 发送消息
	 * @param type
	 * @param info
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(char type, Info info) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			if(info.getContext() != null && info.getContext().length() > 0) {
				Member member = new Member();
				List<Member> list = null;
				switch(type) {
					case 'n':
						list = new LinkedList();
						if(info.getUserid()!=null && info.getUserid().length()>0) {
							member = memberService.find(info.getUserid());
							if(member != null) list.add(member);
						}else if(info.getUsername() != null && info.getUsername().length()>0) {
								String[] userNames = info.getUsername().split(",");
								for(String userName : userNames) {
									member = memberService.findMemberByUsername(userName);
									if(member != null) list.add(member);
								}
						}
						break;
					case 'p':
						member.setUserType("0");
						list = memberService.query(member);
						break;
					case 'e':
						member.setUserType("1");
						list = memberService.query(member);
						break;
					case 'a':
						list = memberService.query(member);
						break;
					default:
						if(info!=null && info.getUserid()!=null) {
							list = new ArrayList<>();
							list.add(memberService.find(info.getUserid()));
							info.setTitle("系统消息");
						}
						break;
				}
				if(list != null && list.size() > 0) {
					info.setType("2");
					info.setSendUserId(getUser().getId());
					info.setSendtime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
					for(Member m : list) {
						info.setId(null);
						info.setUserid(m.getId());
						infoService.saveOrUpd(info);
					}
					jsonMap.put("statusCode", 200);
				} else {
					jsonMap.put("statusCode", 202);
				}
			} else {
				jsonMap.put("statusCode", 201);
			}
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "消息保存异常！", e);
		}
		return jsonMap;
	}

}